package com.study.manage.mvc.org.password;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.UserRepository;
import com.study.manage.domain.User;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.EmailDto;
import com.study.manage.dto.SessionUser;
import com.study.manage.mvc.common.BaseController;
import com.study.manage.utils.Ids;

@Controller
@Scope("request")
@RequestMapping("org/acc")
public class ModifyPasswordController extends BaseController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(path = "pwd", method = RequestMethod.GET)
    public String conf(ModelMap model) {

        SessionUser currentUser = (SessionUser) session.getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        map.put("phone", currentUser.getPhone());
        model.put("data", map);
        // model.put("identityFlg", currentUser.getIdentityFlg());
        return "org/acc/password";
    }

    @ResponseBody
    @RequestMapping(path = "save_password", method = RequestMethod.POST)
    public AjaxResponse conf_pass_save(ModifyPasswordForm form, ModelMap model) throws Exception {

        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser currentUser = (SessionUser) session.getAttribute("user");
        String sCode = (String) session.getAttribute(PASS_CODE_NAME);
        if (EmailDto.checkPhoneCode(sCode, form.getCode())) {
            return ajax.setMsg("手机验证码错误").setCode("002");
        };
        User user = userRepository.findOne(currentUser.getId());
        user.salt = Ids.randomBase62(64);
        user.hashPassword = hashPassword(form.getPassword(), scret, user.salt);
        userRepository.save(user);
        return ajax;
    }

    @ResponseBody
    @RequestMapping(path = "conf-pass_code", method = RequestMethod.POST)
    public AjaxResponse conf_pass_code(String phone) throws Exception {

        AjaxResponse ajax = new AjaxResponse(true);
        sendPhoneCode("PASS_CODE_NAME", phone);
        return ajax;
    }
}
